package com.qf.mybatisplus.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.mybatisplus.bean.dto.UserDto;
import com.qf.mybatisplus.bean.entity.VHdcallspecail;
import com.qf.mybatisplus.bean.entity.VJhmx;
import com.qf.mybatisplus.bean.vo.UserBackVo;
import com.qf.mybatisplus.bean.vo.UserCreateVo;
import com.qf.mybatisplus.resultBean.JsonResult;
import com.qf.mybatisplus.bean.entity.User;
import com.qf.mybatisplus.mapper.UserMapper;
import com.qf.mybatisplus.resultBean.ResultCode;
import com.qf.mybatisplus.service.StudentService;
import com.qf.mybatisplus.service.UserService;
import com.qf.mybatisplus.test.Test04;
import com.qf.mybatisplus.test.TestThread;
import com.qf.mybatisplus.utils.FileUtils;
import com.qf.mybatisplus.utils.PageUtils;
import com.qf.mybatisplus.utils.ThreadPoolUtil;
import com.qf.mybatisplus.utils.excel.ExcelUtil;
import com.qf.mybatisplus.vo.UserInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-05-17
 */
@Controller
@RequestMapping("/user")
@Api(tags = " User测试接口文档")
public class UserController {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;


    /**
     * 根据 id 进行查询
     *
     * @return
     */
    @GetMapping("/getOneUserByUserId/{userId}")
    @ResponseBody
    @ApiOperation(value = "根据用户id获取用户信息")
    public JsonResult getOneUserByUserId(@PathVariable Integer userId) {
        UserBackVo userBackVo = userService.getOneUserByUserId(userId);
        return JsonResult.resultOk(userBackVo);
    }

    /**
     * 查询全部用户
     */
    @PostMapping("/list")
    @ResponseBody
    @ApiOperation(value = "获取所有用户信息列表")
    public JsonResult testSelectList(Integer pagesize,Integer currentPage) {
        PageHelper.startPage(currentPage,pagesize);
        List<User> userList = userService.getUserListInfo(pagesize,currentPage);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return JsonResult.resultOk(pageInfo);
    }

    @GetMapping("/list")
    @ResponseBody
    @ApiOperation(value = "获取所有用户信息列表")
    public JsonResult getSelectList(Integer pagesize,Integer currentPage) {
        PageHelper.startPage(currentPage,pagesize);
        List<User> userList = userService.list(new LambdaQueryWrapper<User>().orderByDesc(User::getCreateTime));
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return JsonResult.resultOk(pageInfo);
    }

    /**
     * 查询全部用户
     */
    @GetMapping("/userList")
    @ResponseBody
    @ApiOperation(value = "获取所有用户信息列表")
    public JsonResult getSelectList(HttpServletResponse response) {

        PageHelper.startPage(2,10);
        List<User> userList = userService.list();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        System.err.println(pageInfo);

        return JsonResult.resultOk(userList);
    }

    /**
     * 查询全部用户并导出到excel,使用ExportExcelUtil工具类
     */
//    @GetMapping("/toExcel")
//    @ApiOperation(value = "查询全部用户并导出到excel")
//    public void exportExcel(HttpServletResponse response) {
//
//        List<User> userList = userService.list();
//
//        String title = "用户信息表";
//        String[] headers = { "序号","id","姓名","密码","年龄","邮箱","联系方式","页码","是否已删除","版本号","创建时间","修改时间"};
//        List<Object[]> dataList = new ArrayList<>();
//        for (User user : userList) {
//            dataList.add(new Object[]{user.getId(),user.getName(),user.getPassword(),user.getAge(),user.getEmail(),user.getPhone(),user.getPagePicture(),user.getVersion(),user.getCreateTime(),user.getUpdateTime()});
//        }
//        // 将表格导出到指定位置
//        try {
//            OutputStream out = new FileOutputStream("C:\\桌面\\用户信息表.xlsx");
//            ExportExcelUtil.exportMessageExcelFile(title, headers, dataList, out, "yyyy-MM-dd");
//            ExportExcelUtil.downloadExcelFile("用户信息表",headers,dataList,response);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        // 浏览器访问下载excel表格
//        // ExportExcelUtil.downloadExcelFile("用户信息表",headers,dataList,response);
//
//    }

    /**
     * 查询全部用户并导出到excel,使用huTool工具写的ExcelUtil工具类
     */
    @GetMapping("/exportExcelUsers")
    @ResponseBody
    @ApiOperation(value = "查询全部用户并导出到excel")
    public String ExportExcelUsers(HttpServletResponse response) {
        List<User> users = userMapper.selectList(null);

        String filePath = "D:\\qianfeng\\mybatisPlusFile\\";
        String fileName = "test.xlsx";
        String title = "test";
        // 设置表头
        // 有序，按照自己设定的表头顺序输出
        Map<String,String> headMap = new LinkedHashMap<>();
        headMap.put("id","编号");
        headMap.put("password","密码");
        headMap.put("name","姓名");
        headMap.put("email","邮箱");
        headMap.put("phone","电话");
        headMap.put("age","年龄");
        headMap.put("createTime","创建时间");
        headMap.put("updateTime","更新时间");
        headMap.put("version","版本号");
        headMap.put("deleted","是否已删除");
        headMap.put("pagePicture","照片地址");
        // 将excel输出到指定文件夹
        try {
            ExcelUtil.exportExcel(users,headMap,new FileOutputStream(filePath+fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // web浏览器直接下载excel
//        ExcelUtil.downloadExcelFile(users,headMap,title,response);
        return "success";
    }

    /**
     * 导入excel
     */
    @PostMapping("/importExcelUsers")
    @ResponseBody
    @ApiOperation(value = "导入excel阜宁大屏数据" )
    @ApiImplicitParam(name = "excel", value = "阜宁大屏数据excel文件",dataType = "file")
    public JsonResult importExcelUsers(MultipartFile excel) {
        File excelFile = null;
        try {
            excelFile = FileUtils.multipartFileToFile(excel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 有序，按照自己设定的表头顺序输出
        Map<String,String> headMap = new LinkedHashMap<>();
        headMap.put("SerialID","serialId");
        headMap.put("CureGroupNo","cureGroupNo");
        headMap.put("CustName","custName");
        headMap.put("groupname","groupName");
        headMap.put("Qno","qno");
        headMap.put("ID","id");
        headMap.put("RegDateTime","regDateTime");
        headMap.put("CureDateTime","cureDateTime");
        headMap.put("Status","status");
        headMap.put("UserID","userId");
        headMap.put("roomno","roomNo");
        headMap.put("AppQStatus","appQStatus");
        headMap.put("departmentid","departmentId");
        headMap.put("departmentname","departmentName");

        List<VJhmx> vJhmxeList = ExcelUtil.importExcel(excelFile, headMap);
        System.err.println(vJhmxeList);
        JsonResult jsonResult = userService.insertVjhmx(vJhmxeList);


        return jsonResult;
    }

    /**
     * 导入excel
     */
    @PostMapping("/importHtCallSpecill")
    @ResponseBody
    @ApiOperation(value = "导入excel")
    public JsonResult importHtCallSpecill(MultipartFile excel) {
        File excelFile = null;
        try {
            excelFile = FileUtils.multipartFileToFile(excel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 有序，按照自己设定的表头顺序输出
        Map<String,String> headMap = new LinkedHashMap<>();
        headMap.put("HardWareID","hardWareId");
        headMap.put("RoomNo","roomNo");
        headMap.put("GroupNO","groupNo");
        headMap.put("GroupName","groupName");
        headMap.put("Specail","specail");

        List<VHdcallspecail> vHdcallspecailList = ExcelUtil.importExcelHt(excelFile, headMap);

        System.err.println(vHdcallspecailList);
        JsonResult jsonResult = userService.insertVHdcallspecail(vHdcallspecailList);


        return jsonResult;
    }
    /**
     * 插入一个用户
     *
     * @return
     */
    @PostMapping("/insertData")
    @ResponseBody
    @ApiOperation(value = "插入一条用户信息")
    public JsonResult insertUser(UserCreateVo userCreateVo) {
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userCreateVo, userDto);
        return userService.insertOneUser(userDto);
    }

    @PostMapping("/saveUser")
    @ResponseBody
    @ApiOperation(value = "插入一条用户信息")
    public JsonResult saveUser(UserCreateVo userCreateVo) {
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userCreateVo, userDto);
        return userService.insertOneUser(userDto);
    }

    /**
     * 根据 id 进行更新
     * 注意：update时生成的sql自动是动态sql：UPDATE user SET age=? WHERE id=?
     */
    @PostMapping("/update")
    @ResponseBody
    @ApiOperation(value = "更新用户信息")
    public JsonResult testUpdateById(@RequestBody User user) {

        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("id", user.getId());
        boolean b = userService.update(user, userUpdateWrapper);

        System.err.println("user=" + user);
        return JsonResult.resultOk(b);
    }

    @PutMapping("/addUser")
    @ResponseBody
    public JsonResult add(@RequestBody User user) {
        System.err.println("user=" + user);
        user.setCreateTime(new Date());
        user.setDeleted(0);
        boolean save = userService.save(user);
        return JsonResult.resultOk(save);
    }


    @DeleteMapping("/delete")
    @ResponseBody
    @ApiOperation(value = "删除一条用户信息")
    public JsonResult deleteUser(String id) {
        System.err.println("id=" + id);
        boolean b = userService.removeById(id);
        System.err.println("b=" + b);
        return JsonResult.resultOk(ResultCode.SUCCESS,b,"成功");
    }

    @GetMapping("/getOne")
    @ResponseBody
    @ApiOperation(value = "根据ID获取一条用户信息")
    public JsonResult getOneUser(String id) {
        System.err.println("id=" + id);
        User user = userService.getById(id);

        return JsonResult.loginOk(user);
    }


    @GetMapping("/readFile")
    @ResponseBody
    @ApiOperation(value = "前端传来文件进行操作文件")
    public JsonResult testReadFile(MultipartFile file) throws Exception {
        File file1 = FileUtils.multipartFileToFile(file);
        FileInputStream fis = new FileInputStream(file1);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);

        String line = "";
        while ((line = br.readLine()) != null) {

            System.out.println(line);
        }
        br.close();
        return JsonResult.loginOk("df");
    }

    @GetMapping("/jsp")
    @ApiOperation(value = "")
    public String testJsp() {

        System.err.println("test");
        return "hello";
    }


    @PostMapping("/batchInsert")
    public void batchInsert(){

        List<User> userList = userService.list();
        // mybatis-plus自带的批量插入方法
        // boolean b = userService.saveBatch(userList);
        // 手写的SQL批量插入
        int i = userService.batchInsert(userList);
        System.err.println(i);

    }


    @ApiOperation(value = "提交资料")
    @PostMapping("/submitResource")
    @ResponseBody
    public JsonResult submitResource(@RequestBody UserInfoVo userInfoVo){
        System.err.println(userInfoVo);
        return JsonResult.resultOk(userInfoVo);
    }

    /**
     * @Description  此种请求 前端axios中参数 为params传进来一个对象 也是将参数拼到路径后面
     * 或者let formData 将参数拼到路径后面 http://localhost:9000/user/submitResource1?name=111&password=11&phone=11&fileUrl=http:%2F%2F192.168.0.66:8091%2FmybatisPlus%2Fgsyh%2F2022%2F04%2F29%2F202204291531035.jpg
     * @param phone
     * @param name
     * @param fileUrl
     * @Author ZDD
     * @return {com.qf.mybatisplus.resultBean.JsonResult}
     * @Date  2022/4/29 15:32
    **/
    @ApiOperation(value = "提交资料1")
    @PostMapping("/submitResource1")
    @ResponseBody
    public JsonResult submitResource1(@RequestParam String phone,@RequestParam String name,@RequestParam String fileUrl){
        System.err.println(phone);
        return JsonResult.resultOk(phone);
    }

    @ApiOperation(value = "提交资料2")
    @PostMapping("/submitResource2")
    @ResponseBody
    public JsonResult submitResource2(@RequestBody Map<String,Object> map){
        System.err.println(map.get("phone"));
        return JsonResult.resultOk(map.get("phone"));
    }

    @ApiOperation(value = "添加缓存")
    @PostMapping("/testSaveCache")
    @ResponseBody
    public JsonResult testSaveCache(@RequestBody User user){
        return JsonResult.resultOk(userService.testSaveCache(user));
    }

    @ApiOperation(value = "清除缓存")
    @PostMapping("/testDeleteCache")
    @ResponseBody
    public JsonResult testDeleteCache(@RequestBody User user){
        userService.testDeleteCache(user);
        return JsonResult.resultOk();
    }
}

